//
//  NetWordUtil.m
//  JMZGO
//
//  Created by apple  on 17/7/13.
//  Copyright © 2017年 JMZ. All rights reserved.
//

#import "NetWordUtil.h"

@implementation NetWordUtil

+ (void)scanWifiInfos:(NSArray *)ssidArray
{
    NSLog(@"1.Start");
    //此处设置的内容会在WiFi列表中每个WiFi下边展示出来
    NSMutableDictionary* options = [[NSMutableDictionary alloc] init];
//    NSMutableData *imageData = (NSMutableData*)UIImageJPEGRepresentation([UIImage imageNamed:@"icon_connect"],0.1);
//    NSData *strdata = [@"🔑金拇指购城市WiFi一键连接" dataUsingEncoding:NSUTF8StringEncoding];
//    [imageData appendData:strdata];
//    [options setObject:imageData forKey:kNEHotspotHelperOptionDisplayName];
    [options setObject:@"🔑金拇指城市WiFi一键连接" forKey: kNEHotspotHelperOptionDisplayName];
    
    dispatch_queue_t queue = dispatch_queue_create("com.jmzgo.item", NULL);
    
    NSLog(@"2.Try");
    BOOL returnType = [NEHotspotHelper registerWithOptions: options queue: queue handler: ^(NEHotspotHelperCommand * cmd) {
        
        NSLog(@"4.Finish");
        NEHotspotNetwork* network;
        if (cmd.commandType == kNEHotspotHelperCommandTypeEvaluate || cmd.commandType == kNEHotspotHelperCommandTypeFilterScanList) {
            // 遍历 WiFi 列表，打印基本信息
            for (network in cmd.networkList) {
                NSString* wifiInfoString = [[NSString alloc] initWithFormat: @"---------------------------\nSSID: %@\nMac地址: %@\n信号强度: %f\nCommandType:%ld\n---------------------------\n\n", network.SSID, network.BSSID, network.signalStrength, (long)cmd.commandType];
                NSLog(@"%@", wifiInfoString);
                
                for (NSDictionary *dict in ssidArray) {
                    // 检测到指定 WiFi 可设定密码直接连接
                    if ([network.SSID isEqualToString:dict[@"wifisid"]]) {
                        [network setConfidence: kNEHotspotHelperConfidenceHigh];
                        [network setPassword:dict[@"wifipas"]];
                        NEHotspotHelperResponse *response = [cmd createResponse: kNEHotspotHelperResultSuccess];
                        NSLog(@"Response CMD: %@", response);
                        [response setNetworkList: @[network]];
                        [response setNetwork: network];
                        [response deliver];
                    }

                }
            }
        }
    }];
    
    // 注册成功 returnType 会返回一个 Yes 值，否则 No
    NSLog(@"3.Result: %@", returnType == YES ? @"Yes" : @"No");
}

+ (NSString *)getWiFiMac
{
    NSString *ssid = @"0";
    NSString *macIp = @"0";
    CFArrayRef myArray =CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict =CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray,0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            ssid = [dict valueForKey:@"SSID"];           //WiFi名称
            macIp = [dict valueForKey:@"BSSID"];     //Mac地址
            NSLog(@"当前连接的SSID为：%@ \nMac地址为：%@",ssid,macIp);
        }
    }
    return macIp;
}

+ (NSString *)getWiFiSSID
{
    NSString *ssid = @"0";
    NSString *macIp = @"0";
    CFArrayRef myArray =CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict =CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray,0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            ssid = [dict valueForKey:@"SSID"];           //WiFi名称
            macIp = [dict valueForKey:@"BSSID"];     //Mac地址
            NSLog(@"当前连接的SSID为：%@ \nMac地址为：%@",ssid,macIp);
        }
    }
    return ssid;
}

+ (NSString *)MacAddress
{
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((CFStringRef)ifnam);
        if (info && [info count]) {
            break;
        }
    }
    
    NSDictionary *dic = (NSDictionary *)info;
    NSString *ssid=[[dic objectForKey:@"SSID"] lowercaseString];
    NSString *bssid =[dic objectForKey:@"BSSID"];
    NSLog(@"ssid:%@ \nbssid:%@",ssid,bssid);
    
    return bssid;
}

+ (NSInteger)networkingStatesFromStatebar
{
    // 状态栏是由当前app控制的，首先获取当前app
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    
    NSString *stateString = @"wifi";
    NSInteger networdType = 0;
    switch (type) {
        case 0:
            networdType = 0;
            stateString = @"notReachable";
            break;
            
        case 1:
            networdType = 2;
            stateString = @"2G";
            break;
            
        case 2:
            networdType = 2;
            stateString = @"3G";
            break;
            
        case 3:
            networdType = 2;
            stateString = @"4G";
            break;
            
        case 4:
            networdType = 2;
            stateString = @"LTE";
            break;
            
        case 5:
            networdType = 1;
            stateString = @"wifi";
            break;
            
        default:
            break;
    }
    
    return type;
}

+ (NSInteger)currentNetWordStatus:(void(^)(NSInteger status))result{
    NSInteger __block type = -1;
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        result(status);
        type = status;
        switch (status) {
            case -1:
                NSLog(@"未知网络");
                break;
            case 0:
                NSLog(@"网络不可达");
                break;
            case 1:
                NSLog(@"GPRS网络");
                break;
            case 2:
                NSLog(@"wifi网络");
                break;
            default:
                break;
        }
    }];

    return type;
}

/**
 *获取WiFi 信息，返回的字典中包含了WiFi的名称、路由器的Mac地址、还有一个Data(转换成字符串打印出来是wifi名称)
 */
+ (NSDictionary *)fetchSSIDInfo {
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    if (!ifs) {
        return nil;
    }
    
    NSDictionary *info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info && [info count]) { break; }
    }
    return info;
}

/**
 *获取WiFi名称
 */
+ (NSString *)fetchWiFiName {
    NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
    if (!ifs) {
        return nil;
    }
    NSString *WiFiName = nil;
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info && [info count]) {
            // 这里其实对应的有三个key:kCNNetworkInfoKeySSID、kCNNetworkInfoKeyBSSID、kCNNetworkInfoKeySSIDData，
            // 不过它们都是CFStringRef类型的
            WiFiName = [info objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
//                        WiFiName = [info objectForKey:@"SSID"];
            break;
        }
    }
    return WiFiName;
}

@end
